﻿using Shop.Model.DB;
using Shop.RemoteModel.LogisticsTemplate.Model;
using Shop.Repository.LinqHelper;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.Model;
using WeDonekRpc.SqlSugar;

namespace Shop.Repository.lmpl
{
    internal class LogisticsTemplateRepository : ShopBaseRepository<DBLogisticsTemplate, long>, ILogisticsTemplateRepository
    {
        public LogisticsTemplateRepository (ISqlClientFactory factory) : base(factory)
        {
        }
        public long Add (LogisticsTemplateDatum datum)
        {
            DBLogisticsTemplate add = datum.ConvertMap<LogisticsTemplateDatum, DBLogisticsTemplate>();
            add.Id = IdentityHelper.CreateId();
            base.Insert(add);
            return add.Id;
        }
        public void SetIsEnable (long id, bool isEnable)
        {
            if (!base.Update(a => a.IsEnable == isEnable, a => a.Id == id))
            {
                throw new ErrorException("shop.logistics.template.set.fail");
            }
        }
        public void SetIsDefault (long id, long cancelId)
        {
            if (!base.Update(new DBLogisticsTemplate[]
            {
                new DBLogisticsTemplate{ Id = id,IsDefault=true },
                new DBLogisticsTemplate{Id=cancelId,IsDefault=false}
            }, "IsDefault"))
            {
                throw new ErrorException("shop.logistics.template.set.fail");
            }
        }

        public Result[] Query<Result> (LTQueryParam query, IBasicPage paging, out int count) where Result : class
        {
            paging.InitOrderBy("Id", true);
            return base.Query<Result>(query.ToWhere(), paging, out count);
        }
    }
}
